var util = require('./util.js');
var app = getApp();

var HOST;

/**
 * 仿ajaxGet的方法
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _Get(url, data, success, fail, iHandleFail) {
  _request('get', url, data, success, fail, iHandleFail);
}

/**
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _Post(url, data, success, fail, iHandleFail) {
  _request('post', url, data, success, fail, iHandleFail);
}

function _request(method, url, data, success, fail, iHandleFail) {
  var userSid = app.getUserSid();
  var alias = app.getAlias();
  var sid = app.globalData.sid;
  var requestObj;
  var header = {};

  HOST = app.getHost();

  method = (method || 'get').toLowerCase();
  url += '?alias=' + alias;
  data = data || {};
  data.userSid = userSid;
  data.sid = sid;

  if (method == 'post') {
    header = {
      'content-type': 'application/x-www-form-urlencoded',
    }
  } else { //get
    // let params = '';

    // Object.keys(data).forEach(function(key) {
    //   var val = data[key];

    //   if (val instanceof Array) {
    //     val.forEach(function(v) {
    //       params += '&' + key + '[]=' + v;
    //     });
    //   } else {
    //     params += '&' + key + '=' + val;
    //   }
    // });
    // url += params;
  }

  // console.log('---req url:', HOST, url);
  requestObj = {
    url: HOST + url,
    header: header,
    method: method,
    success: function(res) {
      // console.log('---res', res);
      var data = res.data;

      if (data.code == 0) {
        typeof success == "function" && success(data);
      } else {
        typeof fail == "function" && fail(data);
        if (iHandleFail) {
          return;
        }
        if (data.code == 107) {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        } else {
          if (data.msg) {
            util.alert(data.msg);
          }
        }
      }
    },
    fail: function(res) {
      // console.log('---req fail:', res);
      typeof fail == "function" && fail(res);
    }
  };

  // if (method == 'post') {
  requestObj.data = data;
  // }

  wx.request(requestObj);
}

module.exports = {
  P: _Post,
  G: _Get
}